package design.mq;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 消费者
 */
public class Consumer implements Runnable{
    private String mame;
    private BlockingQueue<Data> queue;

    public Consumer(String mame, BlockingQueue<Data> queue) {
        this.mame = mame;
        this.queue = queue;
    }
    private static Random r = new Random();

    @Override
    public void run() {
        while(true){
            try {
                Data data = this.queue.poll(5, TimeUnit.SECONDS);
                if(data == null){
                    System.out.println(" 当前消费者：" + mame + ",超过5s无法获取数据，退出监听..." );
                    break;
                }
                // 休眠0-1000ms 模拟耗时
                Thread.sleep(r.nextInt(1000));
                System.out.println(" 当前消费者：" + mame +"消费成功，消费数据为id:" + data.getId());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}
